package com.atguigu.mycloud.Filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 任浩
 * @version 1.0
 * 这是定义的全局过滤器，用来统计访问接口的时间。
 */
@Component
@Slf4j
public class MyGlobalFilter implements GlobalFilter, Ordered {
    private static final String BENGIN_VISIT_TIME = "BENGIN_VISIT_TIME";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(BENGIN_VISIT_TIME,System.currentTimeMillis());
        return chain.filter(exchange).then(Mono.fromRunnable(() ->{
            //得到我们一开始进来方法的访问时间
            Long beginVisitTime = exchange.getAttribute(BENGIN_VISIT_TIME);
            if(beginVisitTime != null){
                //访问了方法。
                log.info("当前访问的url地址为: "+ exchange.getRequest().getPath());
                log.info("访问接口主机: " + exchange.getRequest().getURI().getHost());
                log.info("访问的时间为：" + (System.currentTimeMillis() - beginVisitTime) + "毫秒");
            }
        }));
    }

    /**
     * 设置过滤器的优先级, 数字越小，优先级越高。
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
